package storage

import (
	"github.com/glebarez/sqlite" // CGO-Free SQLite driver
	"gorm.io/gorm"
)

// Connection represents a database connection configuration stored in the database.
type Connection struct {
	gorm.Model
	Alias string `gorm:"unique;not null"`
	Type  string `gorm:"not null"`
	DSN   string `gorm:"not null"`
}

// Store handles the database operations for connection configurations.
type Store struct {
	db *gorm.DB
}

// NewStore initializes a new store, connects to the SQLite database,
// and auto-migrates the Connection schema.
func NewStore(dbPath string) (*Store, error) {
	db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	// Auto-migrate the schema
	err = db.AutoMigrate(&Connection{})
	if err != nil {
		return nil, err
	}

	return &Store{db: db}, nil
}

// AddConnection adds a new connection configuration to the database.
func (s *Store) AddConnection(alias, dbType, dsn string) error {
	conn := Connection{
		Alias: alias,
		Type:  dbType,
		DSN:   dsn,
	}
	return s.db.Create(&conn).Error
}

// RemoveConnection removes a connection configuration from the database by its alias.
func (s *Store) RemoveConnection(alias string) error {
	return s.db.Where("alias = ?", alias).Delete(&Connection{}).Error
}

// GetAllConnections retrieves all connection configurations from the database.
func (s *Store) GetAllConnections() ([]Connection, error) {
	var connections []Connection
	err := s.db.Find(&connections).Error
	return connections, err
} 